"""
@author: Sergiy Tsymbalyuk
"""

import logging
from datetime import datetime

from pylons import tmpl_context as c, url, request
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect

from repoze.what.predicates import in_group
from repoze.what.plugins.pylonshq import ActionProtector

from chowa.lib.base import BaseController, Session, render
from chowa.model.site import BlogPost
from chowa.lib.site.navigation import Tab
from chowa.lib.site.forms import TabularFieldSet

log = logging.getLogger(__name__)

class AdministrationController(BaseController):
    def blog(self):
        c.is_admin = in_group('administrators').is_met(request.environ)
        c.posts = Session.query(BlogPost).filter_by(blog_id=1).order_by('created desc').all()
        fs = TabularFieldSet(BlogPost)
        fs.configure(include=[fs.title, fs.text.textarea(size=(25, 5))])
        c.form = fs.render()
        return render('/site/administration/blog.html')
    
    @ActionProtector(in_group('administrators'))
    def add_post(self):
        if request.method == 'POST':
            fs = TabularFieldSet(BlogPost, Session)
            fs.rebind(data=request.POST)
            fs.configure(include=[fs.title, fs.text])
            fs.model.created = datetime.now()
            fs.model.modified = datetime.now()
            fs.model.blog_id = 1
            fs.sync()
            Session.commit()
        return redirect(url.current(action='blog'))
    
    @ActionProtector(in_group('administrators'))
    def edit_post(self, id):
        post = Session.query(BlogPost).get(id)
        fs = TabularFieldSet(post)
        fs.configure(include=[fs.title, fs.text.textarea(size=(25, 5))])
        if request.method == 'POST':
            fs.rebind(data=request.POST)
            fs.model.modified = datetime.now()
            fs.sync()
            Session.commit()
            return redirect(url.current(action='blog'))
        c.form = fs.render()
        return render('/site/administration/edit_post.html')
